package com.koo.framework.interceptor;

import com.koo.common.utils.MyStrUtil;
import com.koo.common.utils.UserUtils;
import com.koo.common.vo.UserVo;
import com.koo.framework.feign.SystemFeignService;
import org.apache.shiro.util.AntPathMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @Description: 登录拦截器
 * @Created: with IntelliJ IDEA.
 * @author: charlin
 * @createTime: 2020-07-02 18:37
 **/

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemFeignService systemFeignService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/login", uri)
                || antPathMatcher.match("/swagger-ui.html", uri)
                || antPathMatcher.match("/swagger-resources", uri)
                || antPathMatcher.match("/v2/**", uri)
                || antPathMatcher.match("/webjars/**", uri)
                || antPathMatcher.match("/login.html", uri)
                || antPathMatcher.match("/payed/notify", uri);
        if (match) {
            return true;
        }

        String token = request.getHeader("token");
        if(MyStrUtil.isNotEmpty(token)){
            UserVo user = systemFeignService.getUserBytoken(token);
            if(user != null){
                user.setToken(token);
                UserUtils.set(user);
                return true;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

}
